#include <stdio.h>
#include <stdlib.h>

#define SIZE 3

bool connected ( int set[SIZE][2*SIZE], int x1, int x2 );
int findSetNumber ( int set[SIZE][2*SIZE], int number );
void addSet ( int set[SIZE][2*SIZE], int x1, int x2, int setNo );
void addNumberToSet( int set[SIZE][2*SIZE], int number, int setNumber );
void mergeSets ( int set[SIZE][2*SIZE], int set1, int set2 );



int main(){

	int pairs[SIZE][2] ;
	int sets [SIZE][2*SIZE] ;
	int setCounter = 0;
	int p1,p2,s1,s2,i,j;
//initialization of arrays
	for( i=0; i<SIZE; i++ )
	{
		for( j=0; j<2; j++ )
		{
			pairs[i][j] = -1;
		}
	}
	for( i=0; i<SIZE; i++ )
	{
		for( j=0; j<2*SIZE; j++ )
		{
			sets[i][j] = -1;
		}
	}

	printf("Please enter %d integers by leaving a space(%d pairs):",2*SIZE,SIZE);

	for( i=0; i<SIZE; i++)
	{
		scanf("%d%d",&p1,&p2);
		pairs[i][0] = p1;
		pairs[i][1] = p2;
		s1 = findSetNumber( sets, p1 );
		s2 = findSetNumber( sets, p2 );
//Write the code that is going to create and update sets array here

		if( (s1 == -1) && (s2 == -1) )
		{
			addSet( sets, p1, p2, setCounter++ );
		}
		else if( (s1 != -1) && (s2 == -1) )
		{
			addNumberToSet( sets, p2, s1 );
		}
		else if( (s1 == -1) && (s2 != -1) )
		{
			addNumberToSet( sets, p1, s2 );
		}
		else if( (s1 != -1 ) && (s2 != -1) && ( s1 != s2 ) )
		{
			mergeSets( sets, s1, s2 );
		}
		
	}
	while( true )
	{
		printf("\nPlease enter two integers to see whether they are connected:");
		scanf("%d%d",&p1,&p2);
		if( connected( sets, p1, p2 ) )
			printf("\nThey are connected.");
		else
		printf("\nThey are not connected");
	}

	return 0;
}

void addNumberToSet( int set[SIZE][2*SIZE], int number, int setNumber )
{
	int k;
	for(k=0; k<2*SIZE; k++)
	{
		if(set[setNumber][k]==-1)
		set[setNumber][k]=number;
		return;
	}

}
void addSet ( int set[SIZE][2*SIZE], int x1, int x2, int setNo )
{
	set[setNo][0]=x1;
	set[setNo][1]=x2;
}
int findSetNumber ( int set[SIZE][2*SIZE], int number )
{

	int i,k;
	for(i=0; i<SIZE;i++)
	{
		for(k=0; k<(2*SIZE); k++)
		{
			if(number==set[i][k])
				return i;
			
		}
	}
	return -1;

}
bool connected ( int set[SIZE][2*SIZE], int x1, int x2 )
{
	int i,k,temp=0,temp1=1;
	for(i=0;i<(SIZE);i++)
	{
		for(k=0; k<(2*SIZE); k++)
		{
			if(set[i][k]==x1)
				temp=i;
			if(set[i][k]==x2)
				temp1=i;
				
		}
	}
	
	if(temp1==temp)
		return true;
	else
		return false;
	
}
void mergeSets ( int set[SIZE][2*SIZE], int set1, int set2 )
{
	int k;
	for(k=0; k<2*SIZE; k++)
	{
		if(set[set1][k]==-1)
			break;
	}

	set[set1][k]=set[set2][0];
	set[set1][k+1]=set[set2][1];
	set[set2][0]=-1;
	set[set2][1]=-1;

}



		


		



